package com.travel.modules.alipay.worker;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.travel.commons.utils.R;
import com.travel.modules.alipay.entity.OrderForm;
import com.travel.modules.alipay.service.OrderFormService;
import com.travel.modules.asset.service.GoodsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Callable;

public class OrderStatusChecker implements Callable<R> {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    private final OrderFormService orderFormService;

    private final GoodsService goodsService;

    private final String orderId;

    public OrderStatusChecker(String orderId, OrderFormService orderFormService, GoodsService goodsService) {
        this.orderFormService = orderFormService;
        this.goodsService = goodsService;
        this.orderId = orderId;
    }

    @Override
    public R call() throws InterruptedException {
        int time = 0;
        OrderForm form = orderFormService.getOne(new QueryWrapper<OrderForm>().eq("order_id", orderId));
        if (form == null) {
            return R.error("订单不存在");
        }
        Object goodsObj = goodsService.getGoodsObject(form.getGoodsId());
        while (form.getStatus() != 1) {
            if (time >= 10) {
                logger.error("订单号 : " + orderId + ", 用户 : {} 超时等待, 请检查订单状态", form.getUserId());
                return R.error("等待超时，稍后将会进行人工处理，请耐心等待").put("page", form).put("goods", goodsObj);
            }
            form = orderFormService.getOne(new QueryWrapper<OrderForm>().eq("order_id", orderId));
            Thread.sleep(500);
            time++;
        }
        return R.ok().put("page", form)
                     .put("goods", goodsObj);
    }
}
